<template>
  <div class="home">
    <!-- 头部 -->
    <div class="header">
      <h3 class="title">管理员工作台</h3>
      <!-- 注销 -->
      <el-dropdown>
        <span class="el-dropdown-link">
          当前用户：{{ username }}
          <i class="el-icon-arrow-down el-icon--right"></i>
        </span>
        <el-dropdown-menu slot="dropdown">
          <el-button
            :plain="true"
            style="border: none; width: 70px; height: 35px"
            @click="exit()"
          >退出</el-button>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <div class="content">
      <div class="content-left">
        <!-- 左边菜单 -->
        <el-menu
          default-active="1"
          class="el-menu-vertical-demo"
          background-color="#545c64"
          text-color="#fff"
          active-text-color="#5dd5c8"
        >
          <el-menu-item index="1" @click="tabchange(1)">
            <i class="el-icon-user"></i>
            <span slot="title">用户列表</span>
          </el-menu-item>
          <el-menu-item index="2" @click="tabchange(2)">
            <i class="el-icon-office-building"></i>
            <span slot="title">部门结构</span>
          </el-menu-item>
          <el-menu-item index="3" @click="tabchange(3)">
            <i class="el-icon-bell"></i>
            <span slot="title">消息列表</span>
          </el-menu-item>
          <el-menu-item index="4" @click="tabchange(4)">
            <i class="el-icon-folder-add"></i>
            <span slot="title">注册用户</span>
          </el-menu-item>
          <el-menu-item index="5" @click="tabchange(5)">
            <i class="el-icon-folder-add"></i>
            <span slot="title">发布公告</span>
          </el-menu-item>
        </el-menu>
      </div>
      <!-- 用户列表 -->
      <div class="content-right" v-if="tabIndex == 1">
        <div class="searchBtn" style="display: flex">
          <el-input v-model="searchUser" size="big" placeholder="用户名称" />
          <el-button size="small" icon="el-icon-search" style="height: 40px" @click="getUserList()"></el-button>
        </div>
        <!-- 列表数据 -->
        <el-table :data="userList" style="width: 100%" stripe v-loading="loading">
          <el-table-column label="用户名" prop="userName"></el-table-column>
          <el-table-column label="昵称" prop="nikName"></el-table-column>
          <el-table-column label="性别" prop="sex"></el-table-column>
          <el-table-column label="年龄" prop="age"></el-table-column>
          <el-table-column label="密码" prop="passWord"></el-table-column>
          <el-table-column label="电话" prop="phone"></el-table-column>
          <el-table-column label="角色" prop="post"></el-table-column>
          <el-table-column label="创建时间" prop="createTime"></el-table-column>
          <el-table-column align="right">
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit" @click="updateUser(scope.row)">编辑</el-button>
              <el-button type="danger" icon="el-icon-delete" @click="deleteUser(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          @current-change="getUserList"
          :current-page.sync="pageNo_user"
          :page-size="pageSize"
          :total="total_user"
          layout="total, prev, pager, next"
        ></el-pagination>
        <el-dialog :visible.sync="dialogVisible" width="50%" @close="clearComp()">
          <update-user v-if="showComp" :item="UserDetail" :clearComp="clearComp"></update-user>
        </el-dialog>
      </div>

      <!-- 部门列表 -->
      <div class="content-right" v-if="tabIndex == 2">
        <h3>部门结构总览</h3>
        <el-button type="text" icon="el-icon-circle-plus" size="mini" @click="append({id:'0'})"></el-button>
        <el-tree
          :data="orgList"
          show-checkbox
          node-key="id"
          default-expand-all
          :expand-on-click-node="false"
          :props="defaultProps"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <el-button type="text" icon="el-icon-circle-plus" size="mini" @click="append(data)"></el-button>
            <span>{{ node.label }}</span>
            <el-button
              type="text"
              style="color: red"
              size="mini"
              icon="el-icon-remove"
              @click="remove(node, data)"
            ></el-button>
          </span>
        </el-tree>
      </div>

      <!-- 消息列表 -->
      <div class="content-right" v-if="tabIndex == 3">
        <div class="searchBtn" style="display: flex">
          <el-input v-model="searchMessage" size="big" placeholder="标题搜索" />
          <el-button
            size="small"
            icon="el-icon-search"
            style="height: 40px"
            @click="getMessageList()"
          ></el-button>
        </div>
        <!-- 列表数据 -->
        <el-table :data="messageList" style="width: 100%" stripe v-loading="loading">
          <el-table-column label="编号" prop="id"></el-table-column>
          <el-table-column label="标题" prop="title"></el-table-column>
          <el-table-column label="内容" prop="content"></el-table-column>
          <el-table-column label="创建时间" prop="createTime"></el-table-column>
          <el-table-column align="right">
            <template slot-scope="scope">
              <el-button type="danger" icon="el-icon-delete" @click="deleteMessage(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          @current-change="getMessageList"
          :current-page.sync="pageNo_message"
          :page-size="pageSize"
          :total="total_message"
          layout="total, prev, pager, next"
        ></el-pagination>

        <el-dialog :visible.sync="dialogVisible" width="50%" @close="clearComp()"></el-dialog>
      </div>
      <!-- 注册用户 -->
      <div class="content-right" v-if="tabIndex == 4">
        <add-user></add-user>
      </div>
      <!-- 发布公告 -->
      <div class="content-right" v-if="tabIndex == 5">
        <add-message></add-message>
      </div>
    </div>
  </div>
</template>

<script>
import adminRequest from "../request/admin";
import addUser from "../components/addUser";
import addMessage from "../components/addMessage";
import cookie from "js-cookie"; //引入cookie获取token验证
import updateUser from "../components/updateUser.vue";
let id = 1000;
export default {
  data() {
    let orgList = []; //部门列表
    return {
      loading: false, //加载状态开关

      userinfo: null, // 用户信息
      username: "", //用户名
      tabIndex: "1", //tab下标

      pageSize: 10, //每页条数

      userList: [], //用户列表
      searchUser: "",
      pageNo_user: 1,
      total_user: null,

      messageList: [], //消息列表
      searchMessage: "",//消息搜索
      pageNo_message: 1, //页数
      total_message: null, //每页数量

      UserDetail: [], //编辑的user信息
      dialogVisible: false, //编辑框开关
      showComp: true, //子组件的开关

      orgList: orgList, //部门树
      defaultProps: {
        children: "orgs",
        label: "name"
      }
    };
  },

  components: { //组件使用
    addUser,
    addMessage,
    updateUser
  },

  methods: {
    // 关闭对话框
    clearComp() {
      this.dialogVisible = false;
      this.showComp = false;
    },
    // 点击编辑员工信息
    updateUser(item) {
      this.dialogVisible = true;
      this.showComp = true;
      this.UserDetail = item;
      //获取列表信息
      this.getMessageList();
      this.getUserList();
      this.getOrgList();
    },
    // 菜单切换
    tabchange(index) {
      this.tabIndex = index; //主要是将tabIndex变活 只要点击就变化
      this.loading = true; //每次切换都要让加载开关打开
      //获取列表信息
      this.getMessageList();
      this.getUserList();
      this.getOrgList();
    },

    // 退出登录
    exit() {
      window.localStorage.removeItem("userinfo"); //删除用户信息
      cookie.remove("token"); //删除token
      this.$router.push({ path: "/" }); //跳到登录
      this.$message.success("注销成功!");
    },
    // 删除用户
    deleteUser(item) {
      this.$confirm("确定删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          adminRequest.deleteUser(item.id).then(res => {
            if (res.data.code == 200) {
              this.$message.success("删除成功");
              this.getUserList();
            }
          });
        })
        .catch(() => {});
    },

    // 删除消息
    deleteMessage(item) {
      this.$confirm("确定删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => { //确定后删除操作
          adminRequest.deleteMessage(item.id).then(res => {
            if (res.data.code == 200) {
              this.$message.success("删除成功");
              this.getMessageList();
            }
          });
        })
        .catch(() => {});
    },
//添加部门
    append(data) {
      console.log(data);
      if (!data.orgs) {
        this.$set(data, "orgs", []);
      }
      for (var i; i < data.orgs.length; i++) {
        data.orgs.push(data.orgs[i]);
      }
      id = id++;
      var name = prompt("输入部门名称：");
      if (name == ""|| name  == null){
        return
      }
      const newChild1 = {
        id:
          Math.random()
            .toString(36)
            .substr(3, 6) + Date.now().toString(),
        name: name,
        pid: data.id
      }; // 生成一个部门对象

      adminRequest
        .addOrg({ id: newChild1.id, name: newChild1.name, pid: newChild1.pid })
        .then(res => {
          if (res.data.success == true) {
            data.orgs.push(newChild1);
            this.$message.success("发布成功!");
          } else {
            this.$message.error(res.data.message);
          }
        });
    },
//删除部门
    remove(node, data) {
      this.$confirm("确定删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
      adminRequest.deleteOrg(data.id).then(res => {
        if (res.data.success == true) {
          this.getOrgList();
          this.$message.success("删除成功!");
        } else {
          this.$message.error(res.data.message);
        }
      });})
    },

    // 用户列表
    getUserList(page = 1) {
      this.pageNo = page; //默认展示第一页
      adminRequest
        .getUserList({
          pageNo: this.pageNo_user,
          pageSize: this.pageSize_user,
          searchTxt: this.searchUser
        })
        .then(res => {
          if (res.data.code === 200) {
            const result = res.data.result;
            this.total_user = result.total;
            this.userList = result.result;
            setTimeout(() => {
              this.loading = false;
            }, 500);
          }
        });
    },
    //获取消息列表
    getMessageList(page = 1) {
      this.pageNo = page; //默认展示第一页
      adminRequest
        .getMessageList({
          pageNo: this.pageNo_message,
          pageSize: this.pageSize_message,
          searchTxt: this.searchMessage
        })
        .then(res => {
          if (res.data.code === 200) {  //成功操作
            const result = res.data.result;
            this.total_message = result.total;
            this.messageList = result.result;
            setTimeout(() => {
              this.loading = false;
            }, 500);
          }
        });
    },

    // 部门列表
    getOrgList() {
      adminRequest.getorgList({}).then(res => {
        if (res.data.code === 200) {
          const result = res.data.result;
          this.orgList = result;
          console.log(this.orgList);
          setTimeout(() => {
            this.loading = false;
          }, 500);
        }
      });
    }
  },

  created() {
    // 获取本地用户信息
    this.userinfo = JSON.parse(window.localStorage.getItem("userinfo"));
    if (
      this.userinfo == null ||
      this.userinfo == "" ||
      this.userinfo.type != "admin"
    ) {
      // 如果没有用户信息就进不来此页面
      window.localStorage.removeItem("userinfo");
      cookie.remove("token");
      this.$router.push({ path: "/" });
      this.$notify({
        title: "需要登录才能访问哦",
        type: "warning"
      });
    } else {
      this.username = this.userinfo.userName;
    }

    // 页面加载时请求数据
    this.getMessageList();
    this.getUserList();
    this.getOrgList();
  }
};
</script>

<style lang="scss" scoped>
@import "../css/adminHome.scss";
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 14px;
  padding-right: 8px;
  .custom-tree-node-right {
    display: flex;
    margin-left: 100px;
  }
}
</style>
